import { Request, Response } from 'express';
import { CategoryService } from '../services/categoryService';

const categoryService = new CategoryService();

export class CategoryController {
  // 获取所有分类
  async getAllCategories(req: Request, res: Response) {
    try {
      const categories = await categoryService.getAllCategories();

      res.json({
        success: true,
        data: categories,
      });
    } catch (error) {
      console.error('获取分类列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取分类列表失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 根据ID获取分类
  async getCategoryById(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const category = await categoryService.getCategoryById(parseInt(id));

      if (!category) {
        return res.status(404).json({
          success: false,
          message: '分类不存在',
        });
      }

      res.json({
        success: true,
        data: category,
      });
    } catch (error) {
      console.error('获取分类详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取分类详情失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 创建分类
  async createCategory(req: Request, res: Response) {
    try {
      const categoryData = req.body;
      const category = await categoryService.createCategory(categoryData);

      res.status(201).json({
        success: true,
        message: '分类创建成功',
        data: category,
      });
    } catch (error) {
      console.error('创建分类失败:', error);
      res.status(500).json({
        success: false,
        message: '创建分类失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 更新分类
  async updateCategory(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const updateData = req.body;

      const category = await categoryService.updateCategory(parseInt(id), updateData);

      res.json({
        success: true,
        message: '分类更新成功',
        data: category,
      });
    } catch (error) {
      console.error('更新分类失败:', error);
      res.status(500).json({
        success: false,
        message: '更新分类失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }

  // 删除分类
  async deleteCategory(req: Request, res: Response) {
    try {
      const { id } = req.params;

      await categoryService.deleteCategory(parseInt(id));

      res.json({
        success: true,
        message: '分类删除成功',
      });
    } catch (error) {
      console.error('删除分类失败:', error);
      res.status(500).json({
        success: false,
        message: '删除分类失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }
} 